<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="userInfo.authority.includes('admin')"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template #menu="{row,index,size}">
        <el-button text type="primary"
                   icon="el-icon-setting"
                   @click="handleCreate(row)">配置
        </el-button>
        <el-button text
                   type="primary"
                   icon="el-icon-edit"
                   @click="$refs.crud.rowEdit(row,index)">编辑
        </el-button>
        <el-button text
                   type="primary"
                   icon="el-icon-delete"
                   @click="$refs.crud.rowDel(row,index)">删除
        </el-button>
      </template>
      <template #label="{ row }">
        <el-tag size="large" style="cursor:pointer" @click="handleCreate(row)">{{ row.label }}</el-tag>
      </template>
      <template #disabled="{ row }">
        <el-switch
          v-model="row.disabled"
          inline-prompt
          @change="disabledChange(row)"
          active-text="是"
          inactive-text="否"
          :active-value="true"
          :inactive-value="false"
        />
      </template>
      <template #sort="{ row }">
        <el-input-number
          size="small"
          v-model="row.sort"
          @change="sortChange(row)"
          :min="1"
          :max="10000"
        ></el-input-number>
      </template>
      <template #imgBox="{row}">
        <img style="width: 150px;height: 150px" :src="row.logo||defaultLogo" alt="">
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, sort, disabled } from '@/api/iot/edge/flows';
import {mapGetters} from "vuex";
import website from '@/config/website';
import { getToken } from 'utils/auth'
import { validatenull } from '@/utils/validate';

export default {
  name: 'edgeFlows',
  props: {
    source: {
      type: String,
      default: "gateway"
    }
  },
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 12,
        pageSizes: [12, 24, 48, 72, 96, 120],
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 32,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        grid: true,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        dialogType: 'drawer',
        dialogWidth: 600,
        dialogClickModal: false,
        column: [
          {
            label: "标题",
            prop: "label",
            gridRow: true,
            search: true,
            span: 24,
            rules: [{
              required: true,
              message: "请输入标题",
              trigger: "blur"
            }]
          },
          {
            label: "来源",
            prop: "source",
            gridRow: true,
            addDisplay: false,
            editDisplay: false,
            span: 24,
          },
          {
            label: "类型",
            prop: "type",
            gridRow: true,
            addDisplay: false,
            editDisplay: false,
            value: "tab",
            span: 24,
          },
          {
            label: '图标',
            type: 'upload',
            listType: 'picture-img',
            dataType: 'string',
            propsHttp: {
              res: 'data',
              url: 'link',
            },
            action: '/blade-resource/oss/endpoint/put-file',
            tip: '只能上传jpg/png文件，且不超过500kb',
            row: true,
            hide: true,
            prop: 'logo',
            span: 24,
            gridRow: true,
          },
          {
            label: "是否禁用",
            prop: "disabled",
            type: "radio",
            dicUrl: "/blade-system/dict/dictionary?code=yes_no",
            dataType: "number",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            value: 0,
            rules: [{
              required: true,
              message: "请配置是否禁用",
              trigger: "blur"
            }],
            slot: true,
            width: 90,
            span: 24,
            addDisplay: false,
            gridRow: true,
          },
          {
            label: "排序号",
            prop: "sort",
            type: "number",
            slot: true,
            value: 999,
            width: 180,
            span: 24,
            gridRow: true,
            rules: [{
              required: true,
              message: "请配置发布状态",
              trigger: "blur"
            }],
          },
          {
            label: "JSON配置",
            prop: "flowData",
            type: "textarea",
            hide: true,
            gridRow: true,
            disabled: true,
            addDisplay: false,
            minRows: 6,
            span: 24,
          },
          {
            label: "说明",
            prop: "info",
            component: 'avue-ueditor',
            action: '/blade-resource/oss/endpoint/put-file',
            propsHttp: {
              res: 'data',
              url: 'link',
            },
            hide: true,
            minRows: 6,
            span: 24,
            gridRow: true,
          },
          {
            label: "部署时间",
            prop: "deployTime",
            gridRow: true,
            addDisplay: false,
            editDisplay: false,
            span: 24,
          },
          {
            label: '',
            prop: 'imgBox',
            display: false,
          },
        ]
      },
      data: []
    };
  },
  computed: {
    website() {
      return website
    },
    ...mapGetters(["userInfo", "permission"]),
    permissionList() {
      return {
        addBtn: this.validData(this.userInfo.authority.includes('admin'), false),
        viewBtn: this.validData(this.userInfo.authority.includes('admin'), false),
        delBtn: this.validData(this.userInfo.authority.includes('admin'), false),
        editBtn: this.validData(this.userInfo.authority.includes('admin'), false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    defaultLogo() {
      const basePath = import.meta.env.VITE_APP_BASE;
      const logoPath = `/svg/icon4.svg`;
      return basePath === "/" ? logoPath : `${basePath}${logoPath}`;
    },
  },
  methods: {
    rowSave(row, done, loading) {
      row.source = this.source;
      add(row).then((res) => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        if (!validatenull(res.data.data)) {
          row.id = res.data.data;
          this.$confirm('是否进行在线配置?', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            this.handleCreate(row);
          });
        }
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      row.source = this.source;
      row.flowData = null;
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleCreate(row) {
      window.open(`${website.design.edgeUrl}/#flow/${row.id}?token=${getToken()}`);
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    disabledChange(row) {
      if (!row.id) {
        return;
      }
      disabled(row).then(
        () => {
          this.onLoad(this.page);
        },
        error => {
          window.console.log(error);
        }
      );
    },
    sortChange(row) {
      if (!row.id) {
        return;
      }
      sort(row).then(
        () => {
          this.onLoad(this.page);
        },
        error => {
          window.console.log(error);
        }
      );
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query, {source: this.source})).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
.imgBox {
  .avue-crud__grid__value {
    position: absolute;
    width: 150px;
    height: 150px;
    right: 20px;
    bottom: 55px;

    img {
      width: 100%;
      height: 100%;
    }
  }

  .avue-crud__grid__label {
    &:after {
      display: none;
    }
  }
}
</style>

